<template>
  <div class="error-test-container">
    <div class="header">
      <BackButton />
      <h1>错误测试页面</h1>
    </div>
    
    <div class="test-section">
      <h2>服务器状态测试</h2>
      <div class="status-info">
        <p>HTTP服务器状态: <span :class="httpStatus ? 'status-running' : 'status-stopped'">
          {{ httpStatus ? '运行中' : '已停止' }}
        </span></p>
        <p>WebSocket服务器状态: <span :class="wsStatus ? 'status-running' : 'status-stopped'">
          {{ wsStatus ? '运行中' : '已停止' }}
        </span></p>
      </div>
      
      <div class="test-buttons">
        <button @click="checkServerStatus" class="test-btn info-btn">
          检查服务器状态
        </button>
        <button @click="startHttpServer" class="test-btn start-btn">
          启动HTTP服务器
        </button>
        <button @click="resetWebSocketStatus" class="test-btn reset-btn">
          重置WebSocket状态
        </button>
      </div>
      
      <div class="log-section">
        <h3>测试日志</h3>
        <div class="log-container">
          <div v-for="(log, index) in logs" :key="index" class="log-item" :class="log.type">
            <span class="log-time">{{ log.time }}</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
        </div>
        <button @click="clearLogs" class="clear-btn">清空日志</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import BackButton from '../components/common/BackButton.vue'
import { showError, showSuccess } from '../utils/snackbar'
import { invoke } from '@tauri-apps/api/core'

const httpStatus = ref(false)
const wsStatus = ref(false)
const logs = ref<Array<{time: string, message: string, type: string}>>([])

const addLog = (message: string, type: 'info' | 'error' | 'success' = 'info') => {
  const now = new Date()
  const timeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`
  logs.value.unshift({
    time: timeStr,
    message,
    type
  })
  // 限制日志数量
  if (logs.value.length > 50) {
    logs.value = logs.value.slice(0, 50)
  }
}


const checkServerStatus = async () => {
  try {
    addLog('检查服务器状态...', 'info')
    const httpResult = await invoke('check_http_server_status')
    const wsResult = await invoke('check_websocket_server_status')
    
    httpStatus.value = httpResult as boolean
    wsStatus.value = wsResult as boolean
    
    addLog(`HTTP服务器: ${httpStatus.value ? '运行中' : '已停止'}`, httpStatus.value ? 'success' : 'error')
    addLog(`WebSocket服务器: ${wsStatus.value ? '运行中' : '已停止'}`, wsStatus.value ? 'success' : 'error')
  } catch (error) {
    addLog(`检查服务器状态失败: ${error}`, 'error')
    showError(`检查服务器状态失败: ${error}`, 5000)
  }
}

const startHttpServer = async () => {
  try {
    addLog('尝试启动HTTP服务器...', 'info')
    // 在APK环境中，我们需要使用应用内的资源路径
    // 这里使用一个相对路径，让后端自动处理路径解析
    const result = await invoke('start_http_server', {
      port: 3030,
      staticDir: 'dist'  // 移除 './' 前缀，让后端处理路径
    })
    addLog(`HTTP服务器启动结果: ${result}`, 'success')
    showSuccess(`HTTP服务器启动成功: ${result}`, 3000)
  } catch (error) {
    addLog(`HTTP服务器启动失败: ${error}`, 'error')
    showError(`HTTP服务器启动失败: ${error}`, 8000)
  }
}

const resetWebSocketStatus = async () => {
  try {
    addLog('重置WebSocket服务器状态...', 'info')
    const result = await invoke('reset_websocket_server_status')
    addLog(`WebSocket状态重置结果: ${result}`, 'success')
    showSuccess(`WebSocket状态已重置: ${result}`, 3000)
    // 重新检查状态
    await checkServerStatus()
  } catch (error) {
    addLog(`重置WebSocket状态失败: ${error}`, 'error')
    showError(`重置WebSocket状态失败: ${error}`, 5000)
  }
}

const clearLogs = () => {
  logs.value = []
  addLog('日志已清空', 'info')
}

onMounted(() => {
  addLog('错误测试页面已加载', 'info')
  checkServerStatus()
})
</script>

<style scoped>
.error-test-container {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
  color: white;
}

.header {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 2rem;
}

.header h1 {
  font-size: 2rem;
  color: #fff;
}

.test-section {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 2rem;
}

.test-section h2 {
  color: #fff;
  margin-bottom: 1rem;
}

.status-info {
  margin-bottom: 2rem;
  padding: 1rem;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
}

.status-info p {
  margin: 0.5rem 0;
  font-size: 1.1rem;
}

.status-running {
  color: #4caf50;
  font-weight: bold;
}

.status-stopped {
  color: #f44336;
  font-weight: bold;
}

.test-buttons {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
  margin-bottom: 2rem;
}

.test-btn {
  padding: 1rem 2rem;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.error-btn {
  background: linear-gradient(135deg, #f44336, #d32f2f);
  color: white;
}

.error-btn:hover {
  background: linear-gradient(135deg, #d32f2f, #b71c1c);
  transform: translateY(-2px);
}

.success-btn {
  background: linear-gradient(135deg, #4caf50, #45a049);
  color: white;
}

.success-btn:hover {
  background: linear-gradient(135deg, #45a049, #2e7d32);
  transform: translateY(-2px);
}

.info-btn {
  background: linear-gradient(135deg, #2196f3, #1976d2);
  color: white;
}

.info-btn:hover {
  background: linear-gradient(135deg, #1976d2, #1565c0);
  transform: translateY(-2px);
}

.start-btn {
  background: linear-gradient(135deg, #ff9800, #f57c00);
  color: white;
}

.start-btn:hover {
  background: linear-gradient(135deg, #f57c00, #ef6c00);
  transform: translateY(-2px);
}

.reset-btn {
  background: linear-gradient(135deg, #9c27b0, #7b1fa2);
  color: white;
}

.reset-btn:hover {
  background: linear-gradient(135deg, #7b1fa2, #4a148c);
  transform: translateY(-2px);
}

.log-section {
  margin-top: 2rem;
}

.log-section h3 {
  color: #fff;
  margin-bottom: 1rem;
}

.log-container {
  background: rgba(0, 0, 0, 0.5);
  border-radius: 8px;
  padding: 1rem;
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 1rem;
}

.log-item {
  display: flex;
  gap: 1rem;
  padding: 0.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  font-family: monospace;
}

.log-item:last-child {
  border-bottom: none;
}

.log-item.info {
  color: #e3f2fd;
}

.log-item.success {
  color: #c8e6c9;
}

.log-item.error {
  color: #ffcdd2;
}

.log-time {
  color: #90a4ae;
  min-width: 80px;
}

.log-message {
  flex: 1;
}

.clear-btn {
  padding: 0.5rem 1rem;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.clear-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* 滚动条样式 */
.log-container::-webkit-scrollbar {
  width: 8px;
}

.log-container::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.log-container::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

.log-container::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}
</style>
